package com.sky.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.entity.User;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 统计指定时间区间内的营业额数据
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {

        //turnoverReportVO里面日期对象操作,是表的横轴
        //当前集合用于存放从begin到end范围内的每天日期
        List<LocalDate> dateList=new ArrayList<>();

        dateList.add(begin);
        while (!begin.equals(end)){
            //日期计算，计算指定日期的后一天对应的日期
            begin=begin.plusDays(1);
            dateList.add(begin);
        }
        //org.apache.commons.lang3.StringUtils工具包里面方法封装对应TurnoverReportVO里面要求的前端数据格式
        String joinDateList = StringUtils.join(dateList, ",");


        //turnoverReportVO里面营业额对象操作，是表的纵轴
        //存放每天营业额
        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate date : dateList) {
            //查询data日期对应的营业额数据,营业额是指：状态为“已完成==>Orders对象里面为5”的订单金额合计
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map=new HashMap<>();
            map.put("begin",beginTime);
            map.put("end",endTime);
            map.put("status", Orders.COMPLETED);
            Double turnover = orderMapper.sumByMap(map);


            turnover=(turnover==null)?0.0:turnover;
            turnoverList.add(turnover);
        }
        String joinTurnoverList = StringUtils.join(turnoverList, ",");

        //封装返回结果turnoverReportVO
        TurnoverReportVO turnoverReportVO = TurnoverReportVO.builder()
                .dateList(joinDateList)
                .turnoverList(joinTurnoverList)
                .build();

        return turnoverReportVO;
    }


    /**
     * 统计指定时间区间内的用户数据
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {

        //当前集合用于存放从begin到end范围内的每天日期
        List<LocalDate> dateList=new ArrayList<>();

        dateList.add(begin);
        while (!begin.equals(end)){
            //日期计算，计算指定日期的后一天对应的日期
            begin=begin.plusDays(1);
            dateList.add(begin);
        }
        //org.apache.commons.lang3.StringUtils工具包里面方法封装对应UserReportVO里面要求的前端数据格式
        String joinDateList = StringUtils.join(dateList, ",");

        //存放每天用户新增数量
        List<Long> newUserList = new ArrayList<>();
        //存放每天用户总量
        List<Long> totalUserList = new ArrayList<>();
        for (LocalDate date : dateList) {
            //查询data日期对应的用户数量
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

//            Map map=new HashMap<>();
//            map.put("end",endTime);
//            //总用户数量
//            Integer totalUser=userMapper.countByMap(map);
//            //新增用户数量
//            map.put("begin",beginTime);
//            Integer newUser=userMapper.countByMap(map);

            QueryWrapper<User> queryWrapper=new QueryWrapper<>();
            queryWrapper.lambda().le(User::getCreateTime,endTime);
            Long totalUser=userMapper.selectCount(queryWrapper);
            queryWrapper.lambda().ge(User::getCreateTime,beginTime);
            Long newUser=userMapper.selectCount(queryWrapper);

            totalUserList.add(totalUser);
            newUserList.add(newUser);
        }

        String joinNewUserList = StringUtils.join(newUserList, ",");
        String joinTotalUserList = StringUtils.join(totalUserList, ",");

        UserReportVO userReportVO = UserReportVO.builder()
                .dateList(joinDateList)
                .newUserList(joinNewUserList)
                .totalUserList(joinTotalUserList)
                .build();

        return userReportVO;
    }

    /**
     * 统计指定时间区间内的订单数据
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO getOrdersStatistics(LocalDate begin, LocalDate end) {

        //当前集合用于存放从begin到end范围内的每天日期
        List<LocalDate> dateList=new ArrayList<>();

        dateList.add(begin);
        while (!begin.equals(end)){
            //日期计算，计算指定日期的后一天对应的日期
            begin=begin.plusDays(1);
            dateList.add(begin);
        }
        //org.apache.commons.lang3.StringUtils工具包里面方法封装对应OrderReportVO里面要求的前端数据格式
        String joinDateList = StringUtils.join(dateList, ",");

        //存放每天订单总数
        List<Long> orderCountList=new ArrayList<>();
        //存放每天有效订单数
        List<Long> validOrderCountList=new ArrayList<>();

        //遍历dateList集合，查询每天的有效订单数和订单总数
        for (LocalDate date : dateList) {
            //查询data日期对应的用户数量
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //查询每天订单总数
            Long orderCount = getOrderCount(beginTime, endTime, null);
            //查询每天有效订单数
            Long validOrderCount = getOrderCount(beginTime, endTime, Orders.COMPLETED);
            //将每天订单总数添加到集合
            orderCountList.add(orderCount);
            //将每天有效订单数添加到集合
            validOrderCountList.add(validOrderCount);
        }

        String joinOrderCountList = StringUtils.join(orderCountList, ",");
        String joinValidOrderCountList = StringUtils.join(validOrderCountList, ",");

        //计算时间区间内的订单总数
        Long totalOrderCount = orderCountList.stream().reduce(Long::sum).get();
        //计算时间区间内的有效订单总数
        Long validOrderCount = validOrderCountList.stream().reduce(Long::sum).get();
        //计算订单完成率
        double orderCompletionRate =0.0;
        if (totalOrderCount != 0){
            orderCompletionRate=validOrderCount.doubleValue()/totalOrderCount;
        }

        //封装结果
        OrderReportVO orderReportVO = OrderReportVO.builder()
                .dateList(joinDateList)
                .orderCountList(joinOrderCountList)
                .validOrderCountList(joinValidOrderCountList)
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();

        return orderReportVO;
    }

    /**
     * 根据条件统计订单数量
     * @param begin
     * @param end
     * @param status
     * @return
     */
    private Long getOrderCount(LocalDateTime begin,LocalDateTime end,Integer status){
//        Map map=new HashMap<>();
//        map.put("begin",begin);
//        map.put("end",end);
//        map.put("status",status);
//        return orderMapper.countByMap(map);
        QueryWrapper<Orders>queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda()
                .ge(begin!=null,Orders::getOrderTime,begin)
                .le(end!=null,Orders::getOrderTime,end)
                .eq(status!=null,Orders::getStatus,status);
        Long count = orderMapper.selectCount(queryWrapper);
        return count;
    }

    /**
     * 统计指定时间区间内的销售排名前10
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {

        //转成LocalDateTime
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        //查询指定时间区间内的销售排名前10
        List<GoodsSalesDTO> salesTop10 = orderMapper.getSalesTop10(beginTime, endTime);

//        //构造SalesTop10ReportVO里面数据的List
//        List<String>nameList=new ArrayList<>();
//        List<Integer>numberList=new ArrayList<>();
//
//        //遍历salesTop10封装SalesTop10ReportVO里面的对象
//        for (GoodsSalesDTO goodsSalesDTO : salesTop10) {
//            String goodsSalesDTOName = goodsSalesDTO.getName();
//            Integer goodsSalesDTONumber = goodsSalesDTO.getNumber();
//
//            nameList.add(goodsSalesDTOName);
//            numberList.add(goodsSalesDTONumber);
//        }
//        String joinNameList = StringUtils.join(nameList, ",");
//        String joinNumberList = StringUtils.join(numberList, ",");

        //利用stream流来获取nameList和numberList
        List<String> nameList = salesTop10.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> numberList = salesTop10.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        String joinNameList = StringUtils.join(nameList, ",");
        String joinNumberList = StringUtils.join(numberList, ",");

        //封装对象SalesTop10ReportVO
        SalesTop10ReportVO salesTop10ReportVO = SalesTop10ReportVO.builder()
                .nameList(joinNameList)
                .numberList(joinNumberList)
                .build();

        //返回SalesTop10ReportVO对象
        return salesTop10ReportVO;
    }

    /**
     * 导出运营数据报表
     * @param response
     */
    @Override
    public void exportBusinessData(HttpServletResponse response) {
        //1.查询数据库，获取营业数据---查询最近30天的数据
        LocalDate dateBegin = LocalDate.now().minusDays(30);
        //截至到昨天
        LocalDate dateEnd = LocalDate.now().minusDays(1);

        //精确到时分秒
        LocalDateTime begin = LocalDateTime.of(dateBegin, LocalTime.MIN);
        LocalDateTime end = LocalDateTime.of(dateEnd, LocalTime.MAX);

        //调用service层方法，获取营业数据
        BusinessDataVO businessDataVO = workspaceService.getBusinessData(begin, end);

        //2.通过POI将数据写入Excel文件

        //通过类加载器加在在resource目录下的模板文件
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

        try {
            //基于模板文件创建一个新的Excel文件
            XSSFWorkbook excel = new XSSFWorkbook(in);

            //填充数据--时间
            //获取标签页
            XSSFSheet sheet = excel.getSheet("Sheet1");
            //获取行，获取第二行第二列数据
            sheet.getRow(1).getCell(1).setCellValue("时间："+dateBegin+"至"+dateEnd);

            //继续填充
            //获得行对象,获得第四行
            XSSFRow row = sheet.getRow(3);
            //根据模板Excel对该行的数据进行填充
            //营业额
            row.getCell(2).setCellValue(businessDataVO.getTurnover());
            //订单完成率
            row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            //新增用户数
            row.getCell(6).setCellValue(businessDataVO.getNewUsers());

            //获得第五行
            row = sheet.getRow(4);
            //根据模板Excel对该行的数据进行填充
            //有效订单数
            row.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            //平均订单价格
            row.getCell(4).setCellValue(businessDataVO.getUnitPrice());


            //填充明细数据
            for (int i=0;i<30;i++){
                LocalDate date = dateBegin.plusDays(i);
                //查询某一天的营业数据
                BusinessDataVO businessData = workspaceService.getBusinessData
                        (LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));

                //从第八行开始填充
                row = sheet.getRow(7 + i);

                //对每一行进行填充
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());
            }


            //3.通过输出流，将Excel下载到客户端浏览器
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);

            //关闭资源
            out.close();
            excel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
